package com.boot.admin.modules.sys.ai.service;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

/**
 * 智能文本缓冲和断句服务
 * 
 * @author 李飞洋
 * @date 2025/9/24
 */
@Slf4j
@Service
public class TextBufferService {

    // 存储每个对话的文本缓冲区
    private final ConcurrentHashMap<String, ConversationBuffer> conversationBuffers = new ConcurrentHashMap<>();
    
    // 句子结束符号的正则表达式
    private static final Pattern SENTENCE_END_PATTERN = Pattern.compile("[。！？.!?；;]");
    
    // 中文句子结束符号
    private static final Pattern CHINESE_SENTENCE_END = Pattern.compile("[。！？；]");
    
    // 英文句子结束符号
    private static final Pattern ENGLISH_SENTENCE_END = Pattern.compile("[.!?;]");
    
    // 最小TTS触发长度
    private static final int MIN_TTS_LENGTH = 8;
    
    // 最大TTS缓冲长度（避免句子过长）
    private static final int MAX_TTS_BUFFER_LENGTH = 100;

    /**
     * 对话缓冲区内部类
     */
    public static class ConversationBuffer {
        private final StringBuilder ttsBuffer = new StringBuilder();        // TTS缓冲区
        private final StringBuilder completeContentBuffer = new StringBuilder(); // 完整内容缓冲区
        private final String conversationId;
        private final String messageId;
        private volatile boolean isCompleted = false;
        
        public ConversationBuffer(String conversationId, String messageId) {
            this.conversationId = conversationId;
            this.messageId = messageId;
        }
        
        // 同步方法确保线程安全
        public synchronized void appendText(String text) {
            if (text != null && !text.isEmpty()) {
                ttsBuffer.append(text);
                completeContentBuffer.append(text);
            }
        }
        
        public synchronized String getTtsBufferContent() {
            return ttsBuffer.toString();
        }
        
        public synchronized String getCompleteContent() {
            return completeContentBuffer.toString();
        }
        
        public synchronized void clearTtsBuffer() {
            ttsBuffer.setLength(0);
        }
        
        public synchronized void markCompleted() {
            this.isCompleted = true;
        }
        
        public boolean isCompleted() {
            return isCompleted;
        }
        
        public String getConversationId() {
            return conversationId;
        }
        
        public String getMessageId() {
            return messageId;
        }
    }

    /**
     * 文本处理结果
     */
    public static class TextProcessResult {
        private final List<String> completedSentences;  // 完成的句子列表
        private final boolean hasNewSentence;          // 是否有新句子生成
        private final boolean isStreamCompleted;       // 流是否完成
        private final String remainingText;            // 剩余文本
        
        public TextProcessResult(List<String> completedSentences, boolean hasNewSentence, 
                               boolean isStreamCompleted, String remainingText) {
            this.completedSentences = completedSentences;
            this.hasNewSentence = hasNewSentence;
            this.isStreamCompleted = isStreamCompleted;
            this.remainingText = remainingText;
        }
        
        public List<String> getCompletedSentences() { return completedSentences; }
        public boolean hasNewSentence() { return hasNewSentence; }
        public boolean isStreamCompleted() { return isStreamCompleted; }
        public String getRemainingText() { return remainingText; }
    }

    /**
     * 初始化对话缓冲区
     */
    public ConversationBuffer initializeBuffer(String conversationId, String messageId) {
        ConversationBuffer buffer = new ConversationBuffer(conversationId, messageId);
        conversationBuffers.put(getBufferKey(conversationId, messageId), buffer);
        log.debug("初始化文本缓冲区 - 对话: {}, 消息: {}", conversationId, messageId);
        return buffer;
    }

    /**
     * 处理新的文本块
     */
    public TextProcessResult processTextChunk(String conversationId, String messageId, String textChunk) {
        String bufferKey = getBufferKey(conversationId, messageId);
        ConversationBuffer buffer = conversationBuffers.get(bufferKey);
        
        if (buffer == null) {
            log.warn("未找到缓冲区 - 对话: {}, 消息: {}", conversationId, messageId);
            return new TextProcessResult(new ArrayList<>(), false, false, "");
        }
        
        // 添加文本到缓冲区
        buffer.appendText(textChunk);
        
        // 分析当前TTS缓冲区内容
        String currentTtsContent = buffer.getTtsBufferContent();
        
        // 使用智能断句识别完成的句子
        List<String> completedSentences = extractCompletedSentences(currentTtsContent, buffer);
        
        boolean hasNewSentence = !completedSentences.isEmpty();
        
        log.debug("文本处理结果 - 对话: {}, 新句子数: {}, TTS缓冲区长度: {}", 
                 conversationId, completedSentences.size(), currentTtsContent.length());
        
        return new TextProcessResult(completedSentences, hasNewSentence, false, currentTtsContent);
    }

    /**
     * 标记流结束并处理剩余文本
     */
    public TextProcessResult markStreamCompleted(String conversationId, String messageId) {
        String bufferKey = getBufferKey(conversationId, messageId);
        ConversationBuffer buffer = conversationBuffers.get(bufferKey);
        
        if (buffer == null) {
            log.warn("未找到缓冲区进行结束处理 - 对话: {}, 消息: {}", conversationId, messageId);
            return new TextProcessResult(new ArrayList<>(), false, true, "");
        }
        
        buffer.markCompleted();
        
        // 处理剩余的TTS缓冲区内容
        String remainingTtsContent = buffer.getTtsBufferContent().trim();
        List<String> finalSentences = new ArrayList<>();
        
        if (!remainingTtsContent.isEmpty() && remainingTtsContent.length() >= MIN_TTS_LENGTH) {
            // 如果剩余内容足够长，作为最后一个句子
            finalSentences.add(remainingTtsContent);
            buffer.clearTtsBuffer();
        }
        
        String completeContent = buffer.getCompleteContent();
        
        log.info("流结束处理完成 - 对话: {}, 消息: {}, 完整内容长度: {}, 最终句子数: {}", 
                conversationId, messageId, completeContent.length(), finalSentences.size());
        
        return new TextProcessResult(finalSentences, !finalSentences.isEmpty(), true, completeContent);
    }

    /**
     * 提取已完成的句子
     */
    private List<String> extractCompletedSentences(String text, ConversationBuffer buffer) {
        List<String> sentences = new ArrayList<>();
        
        if (StringUtils.isBlank(text)) {
            return sentences;
        }
        
        try {
            // 优先使用HanLP进行智能断句
            sentences = extractSentencesWithHanLP(text, buffer);
            
            if (sentences.isEmpty()) {
                // 备用方案：使用正则表达式断句
                sentences = extractSentencesWithRegex(text, buffer);
            }
            
        } catch (Exception e) {
            log.warn("HanLP断句失败，使用正则表达式备用方案", e);
            sentences = extractSentencesWithRegex(text, buffer);
        }
        
        return sentences;
    }

    /**
     * 使用HanLP进行智能断句
     */
    private List<String> extractSentencesWithHanLP(String text, ConversationBuffer buffer) {
        List<String> sentences = new ArrayList<>();
        
        try {
            // 使用HanLP进行分句
            List<String> hanLPSentences = HanLP.extractSummary(text, 10); // 提取关键句子
            
            if (hanLPSentences.isEmpty()) {
                // 如果HanLP提取失败，使用简单的分词结合句号识别
                return extractSentencesWithSimpleLogic(text, buffer);
            }
            
            // 检查是否有完整句子
            for (String sentence : hanLPSentences) {
                if (sentence.trim().length() >= MIN_TTS_LENGTH && 
                    SENTENCE_END_PATTERN.matcher(sentence).find()) {
                    sentences.add(sentence.trim());
                }
            }
            
        } catch (Exception e) {
            log.debug("HanLP处理失败，降级到简单逻辑", e);
            return extractSentencesWithSimpleLogic(text, buffer);
        }
        
        // 如果找到完整句子，清空对应的TTS缓冲区内容
        if (!sentences.isEmpty()) {
            String processedText = String.join("", sentences);
            String remainingText = text.substring(text.lastIndexOf(processedText) + processedText.length());
            buffer.clearTtsBuffer();
            buffer.appendText(remainingText); // 保留未处理的部分
        }
        
        return sentences;
    }

    /**
     * 使用简单逻辑进行断句
     */
    private List<String> extractSentencesWithSimpleLogic(String text, ConversationBuffer buffer) {
        List<String> sentences = new ArrayList<>();
        
        // 简单的断句逻辑：查找句号、感叹号、问号
        String[] possibleSentences = SENTENCE_END_PATTERN.split(text);
        
        if (possibleSentences.length > 1) {
            // 有完整句子
            for (int i = 0; i < possibleSentences.length - 1; i++) {
                String sentence = possibleSentences[i].trim();
                if (sentence.length() >= MIN_TTS_LENGTH) {
                    // 重新添加句号（因为split会移除）
                    if (!sentence.matches(".*[。！？.!?；;]$")) {
                        sentence += "。";
                    }
                    sentences.add(sentence);
                }
            }
            
            // 更新TTS缓冲区，只保留最后一个未完成的部分
            if (possibleSentences.length > 0) {
                String remainingText = possibleSentences[possibleSentences.length - 1].trim();
                buffer.clearTtsBuffer();
                if (!remainingText.isEmpty()) {
                    buffer.appendText(remainingText);
                }
            }
        } else {
            // 检查是否缓冲区太长，需要强制分割
            if (text.length() > MAX_TTS_BUFFER_LENGTH) {
                return forceExtractSentence(text, buffer);
            }
        }
        
        return sentences;
    }

    /**
     * 使用正则表达式进行断句（备用方案）
     */
    private List<String> extractSentencesWithRegex(String text, ConversationBuffer buffer) {
        return extractSentencesWithSimpleLogic(text, buffer);
    }

    /**
     * 强制提取句子（当缓冲区过长时）
     */
    private List<String> forceExtractSentence(String text, ConversationBuffer buffer) {
        List<String> sentences = new ArrayList<>();
        
        // 寻找最近的逗号或其他分隔符进行分割
        String[] parts = text.split("[，,、]");
        
        if (parts.length > 1) {
            StringBuilder sentenceBuilder = new StringBuilder();
            for (int i = 0; i < parts.length - 1; i++) {
                sentenceBuilder.append(parts[i]).append("，");
            }
            
            String forcedSentence = sentenceBuilder.toString().trim();
            if (forcedSentence.length() >= MIN_TTS_LENGTH) {
                sentences.add(forcedSentence);
                
                // 保留最后一部分
                buffer.clearTtsBuffer();
                String remaining = parts[parts.length - 1].trim();
                if (!remaining.isEmpty()) {
                    buffer.appendText(remaining);
                }
            }
        }
        
        return sentences;
    }

    /**
     * 获取完整内容
     */
    public String getCompleteContent(String conversationId, String messageId) {
        String bufferKey = getBufferKey(conversationId, messageId);
        ConversationBuffer buffer = conversationBuffers.get(bufferKey);
        
        if (buffer != null) {
            return buffer.getCompleteContent();
        }
        
        return "";
    }

    /**
     * 清理缓冲区
     */
    public void cleanupBuffer(String conversationId, String messageId) {
        String bufferKey = getBufferKey(conversationId, messageId);
        ConversationBuffer removed = conversationBuffers.remove(bufferKey);
        
        if (removed != null) {
            log.debug("清理文本缓冲区 - 对话: {}, 消息: {}", conversationId, messageId);
        }
    }

    /**
     * 获取缓冲区状态
     */
    public boolean isBufferCompleted(String conversationId, String messageId) {
        String bufferKey = getBufferKey(conversationId, messageId);
        ConversationBuffer buffer = conversationBuffers.get(bufferKey);
        
        return buffer != null && buffer.isCompleted();
    }

    /**
     * 获取活跃缓冲区数量
     */
    public int getActiveBufferCount() {
        return conversationBuffers.size();
    }

    /**
     * 生成缓冲区键
     */
    private String getBufferKey(String conversationId, String messageId) {
        return conversationId + ":" + messageId;
    }

    /**
     * 清理过期的缓冲区（可以通过定时任务调用）
     */
    public void cleanupExpiredBuffers() {
        conversationBuffers.entrySet().removeIf(entry -> {
            ConversationBuffer buffer = entry.getValue();
            return buffer.isCompleted();
        });
        
        log.debug("清理过期缓冲区完成，当前活跃缓冲区数量: {}", conversationBuffers.size());
    }
}